﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WeiBeeCommon.Helpers;

namespace SofaExpert
{
    /// <summary>
    /// Interaction logic for SetKeyword.xaml
    /// </summary>
    public partial class SetKeyword : Window
    {
        public SetKeyword()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            textBoxKeywords.Text = ReadKeywords();
            _changed = false;
        }

        private string ReadKeywords()
        {
            SearchHelper searchHelper = new SearchHelper();
            var keywords = searchHelper.Load();
            StringBuilder sb = new StringBuilder();
            foreach (var word in keywords.Keywords)
            {
                sb.AppendLine(word);
            }
            return sb.ToString();
        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        private void buttonOk_Click(object sender, RoutedEventArgs e)
        {
            if (_changed)
            {
                var newkeywords = textBoxKeywords.Text.Split(
                    System.Environment.NewLine.ToCharArray(), 
                    StringSplitOptions.RemoveEmptyEntries);
                var sk = new SearchKeywords { City = "", Keywords = newkeywords.ToList() };
                (new SearchHelper()).Save(sk);
                this.DialogResult = true;
            }
            this.Close();
        }

        private bool _changed = false;
        private void textBoxKeywords_TextChanged(object sender, TextChangedEventArgs e)
        {
            _changed = true;
        }
    }
}
